package cn.com.assistant.utils;

import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class RequestUtil {
    public RequestUtil() {
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return null == servletRequestAttributes ? null : servletRequestAttributes.getRequest();
    }

    public static String getAccessToken(HttpServletRequest request) {
        return request.getParameter("access_token");
    }

    public static String getAccessToken() {
        HttpServletRequest request = getRequest();
        if (null == request) {
            return null;
        } else {
            String token = request.getParameter("access_token");
            if (null != token) {
                return token;
            } else {
                return request.getAttribute("access_token") == null ? null : String.valueOf(request.getAttribute("access_token"));
            }
        }
    }

    public static Map<String, Object> getParameters(ServletRequest request) {
        return getParametersWithPrefix(request, "");
    }

    public static Map<String, Object> getParametersWithPrefix(ServletRequest request, String prefix) {
        Assert.notNull(request, "Request must not be null");
        Enumeration paramNames = request.getParameterNames();
        Map<String, Object> params = new TreeMap();
        if (prefix == null) {
            prefix = "";
        }

        while(paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String)paramNames.nextElement();
            if ("".equals(prefix) || paramName.startsWith(prefix)) {
                String stripPrefix = paramName.substring(prefix.length());
                String[] values = request.getParameterValues(paramName);
                if (values != null && values.length != 0) {
                    if (values.length > 1) {
                        params.put(stripPrefix, values);
                    } else {
                        params.put(stripPrefix, values[0]);
                    }
                }
            }
        }

        return params;
    }
}